package cn.com.api.controller;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.api.entity.*;
import cn.com.api.service.*;

import cn.com.util.DateUtil;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_API + "erp/")
public class ApiErpController {
	
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiGoodsService goodService;
	@Autowired
	private ApiT_productsService apiT_productsService;
	@Autowired
	private ApiShopsService apiShopsService;
	@Autowired
	private ApiTypeService apitypeService;
	@Autowired
	private ApiErpService apiErpService;
	@Autowired
	private ApiT_erp_logService apiT_erp_logService;
	@Autowired
	private ApiSmslogService apiSmslogService;
	//
	private static Logger logger = Logger
			.getLogger(ApiErpController.class);


	/**
	 * erp 添加货品
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "insertT_products4erp")
	public void insertT_products4erp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String product_id = request.getParameter("product_id");
		String city_id = request.getParameter("city_id");
		String goods_id = request.getParameter("goods_id");
		String mkt_price = request.getParameter("mkt_price");
		String price = request.getParameter("price");
		String pdt_spec = request.getParameter("pdt_spec");
		// 货品条码SKU代码
		String erp_barcode = request.getParameter("erp_barcode");
		String sku_code = request.getParameter("sku_code");
		String erp_product_id = request.getParameter("erp_product_id");
		String erp_goods_sn = request.getParameter("erp_goods_sn");
		//String erp_location = request.getParameter("erp_location");

		String unit = request.getParameter("unit");
		String store = request.getParameter("store");

		Map<String, Object> map = new HashMap<String, Object>();

		if (product_id == null || product_id.trim().isEmpty()) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "请传入货品id, 货品唯一编号,参数product_id");
		} else {	
			//
			try {
				ApiT_products cur_product = apiT_productsService.findT_productsById(Long.valueOf(product_id));
				if(cur_product==null){
					ApiT_products t_product = new ApiT_products();
					t_product.setProduct_id(Long.valueOf(product_id));
					t_product.setGoods_id(Long.valueOf(goods_id));
					t_product.setMkt_price(Util.getBigDecimal(mkt_price));
					t_product.setPrice(Util.getBigDecimal(price));
					t_product.setPdt_spec(pdt_spec);
					t_product.setUnit(unit);
					t_product.setStore(Integer.valueOf(store));
					//product_id ERP中的商品内部码
					erp_product_id = product_id.toString();
					t_product.setErp_product_id(erp_product_id);
					erp_goods_sn = goods_id.toString();
					t_product.setErp_goods_sn(erp_goods_sn);
					// ERP里 基础资料没有机构编码 city_id
					Map<String, String> configMap = startOnLoadService.dictionaryMap();
					if(city_id=="" || city_id==null)
						city_id=  configMap.get("ERP_CITY_ID");
					String shop_id=  configMap.get("ERP_SHOP_ID");
					t_product.setCity_id(Integer.valueOf(city_id));
					t_product.setShop_id(Integer.valueOf(shop_id));
					t_product.setErp_goods_sn(erp_goods_sn);
					t_product.setSource("erp");
					apiErpService.insertT_products4erp(t_product);
					
					//log
					ApiT_erp_log log = new ApiT_erp_log();
					log.setAction("insertT_products4erp");
					log.setGoods_id(goods_id);
					log.setProducts_id(product_id);
					SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					log.setInvoke_time(sFormat.format(new Date()).toString());
					apiT_erp_logService.insertT_erp_log(log);
					
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "erp 添加货品成功！" + goods_id);
				}else{
					// 更新
					cur_product.setMkt_price(Util.getBigDecimal(mkt_price));
					cur_product.setPrice(Util.getBigDecimal(price));
					cur_product.setPdt_spec(pdt_spec);
					cur_product.setUnit(unit);
					cur_product.setStore(Integer.valueOf(store));
					
					
					cur_product.setGoods_id(Long.valueOf(goods_id));
					cur_product.setErp_product_id(erp_product_id);
					erp_goods_sn = goods_id.toString();
					cur_product.setErp_goods_sn(erp_goods_sn);
					
					
					cur_product.setUpdate_time(DateUtil.nowTimeToString());
					int ret_i = apiErpService.updateT_products4erp(cur_product);
					
					//log
					ApiT_erp_log log = new ApiT_erp_log();
					log.setAction("insertT_products4erp_update");
					log.setGoods_id(goods_id);
					log.setProducts_id(product_id);
					log.setRemark("price:"+price+"mkt_price:"+mkt_price+" pdt_spec"+pdt_spec+" unit"+unit +" store"+store);
					SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					log.setInvoke_time(sFormat.format(new Date()).toString());
					apiT_erp_logService.insertT_erp_log(log);
					
					logger.error("已经存在");
					System.out.println("已经存在 "+product_id.toString());
				}

			} catch (Exception e) {
				logger.error(e);
				map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
				map.put(Utils.MESSAGE, "erp 添加货品失败！" + goods_id);
			}
			
		}

		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * erp 添加货品
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "addOrder4erpTask")
	public void addOrder4erpTask(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		apiErpService.addOrder4erpTask();
	}

	/**
	 * erp 同步库存
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "productStock4erpTask")
	public void productStock4erpTask(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String product_id = request.getParameter("product_id");
		
		try{
			ApiT_products cur_product = apiT_productsService.findT_productsById(Long.valueOf(product_id));
			
			apiErpService.productStock4erp(cur_product);
		}catch(Exception e){
			
			logger.error("ERP更新product_id："+product_id+"报错"+e);
		}
		
	}

	/**
	 * 新增erp产品信息（包括产品规格和产品图片）
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "/insertTotalGoods4erp")
	public void insertTotalGoods4erp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String mini_buy = request.getParameter("mini_buy");
		String goods_id = request.getParameter("goods_id");
		String description = request.getParameter("description");
		String type = request.getParameter("type");
		String city_id = request.getParameter("city_id");
		String shop_id = request.getParameter("shop_id");
		String sort = request.getParameter("sort");
		String count = request.getParameter("count");
		String producing_area = request.getParameter("producing_area");
		Map<String, Object> map = new HashMap<String, Object>();
		
		try{
			if (name != null && !"".equals(name.trim())) {
				
				ApiGoods cur_good = goodService.findT_goodsById(Long.valueOf(goods_id));
				if(cur_good == null){
					ApiGoods t_good = new ApiGoods();
					t_good.setId(Long.valueOf(goods_id));
					t_good.setName(name);
					t_good.setType(Integer.valueOf(type));
					t_good.setMini_buy(Integer.valueOf(mini_buy));
					t_good.setDescription(description);
					t_good.setProducing_area(producing_area);
					if (city_id == null)
						city_id = "0";
					if (count == null)
						count = "0";
					t_good.setCount(Integer.valueOf(count));
					if (shop_id == null)
						shop_id = "0";
					if (sort == null)
						sort = "0";
					// ERP里 基础资料没有机构编码 city_id
					Map<String, String> configMap = startOnLoadService.dictionaryMap();
					city_id =  configMap.get("ERP_CITY_ID");
					shop_id =  configMap.get("ERP_SHOP_ID");
					t_good.setCity_id(Integer.valueOf(city_id));
					t_good.setShop_id(Integer.valueOf(shop_id));
					t_good.setSort(Integer.valueOf(sort));
					t_good.setStatus("0"); // 仓库中
					t_good.setSource("erp");
					goodService.insertT_goodsAll4erp(t_good);
					
					//log
					ApiT_erp_log log = new ApiT_erp_log();
					log.setAction("insertTotalGoods4erp");
					log.setGoods_id(goods_id);
					SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					log.setInvoke_time(sFormat.format(new Date()).toString());
					apiT_erp_logService.insertT_erp_log(log);
					
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "添加成功！");
				}else{
					// 更新
					cur_good.setName(name);
					cur_good.setType(Integer.valueOf(type));
					cur_good.setMini_buy(Integer.valueOf(mini_buy));
					cur_good.setDescription(description);
					cur_good.setProducing_area(producing_area);
				
					goodService.updateT_goods4erp(cur_good);
					
					//log
					ApiT_erp_log log = new ApiT_erp_log();
					log.setAction("insertTotalGoods4erp_update");
					log.setGoods_id(goods_id);
					log.setRemark("name:"+name+" type"+type+" mini_buy"+mini_buy +" producing_area"+producing_area);
					SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					log.setInvoke_time(sFormat.format(new Date()).toString());
					apiT_erp_logService.insertT_erp_log(log);
					
					logger.error("已经存在");
					System.out.println("已经存在 "+goods_id.toString());
				}
			}
		}catch(Exception e){
			logger.error(e);
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "添加失败！");
		}
		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}
	
	
	/**
	 * erp 添加分类
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "insertType4erp")
	public void insertType4erp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String c_name = request.getParameter("c_name");
		String c_des = request.getParameter("c_des");
		String c_sid = request.getParameter("c_sid");
		String c_code = request.getParameter("c_code");

		String c_belong = request.getParameter("c_belong");
		String c_grade = request.getParameter("c_grade");
		String c_enable = request.getParameter("c_enable");
		String c_sort = request.getParameter("c_sort");

		Map<String, Object> map = new HashMap<String, Object>();
		ApiType type;
		if (c_code == null || c_code.trim().isEmpty()) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "请传入分类id,参数c_code");
		} else {
			type = apitypeService.findTypeById(Integer.valueOf(c_code));
			if (type != null) {
				type.setcSid(Integer.valueOf(c_sid));
				type.setcName(c_name);
				type.setcDes(c_des);
				type.setcBelong(Integer.valueOf(c_belong));
				type.setcGrade(Integer.valueOf(c_grade));
				type.setcEnable(Integer.valueOf(c_enable));
				type.setcIsziying(1);
				type.setcStatus(1);
				type.setcMod("品类");
				type.setSources("erp");
				
				apitypeService.updateType(type);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, c_code + "已经存在 分类更新成功！");

			} else {
				// add
				if (c_name != null && !"".equals(c_name.trim())) {
					type = new ApiType();
					type.setcCode(Integer.valueOf(c_code));
					type.setcSid(Integer.valueOf(c_sid));
					type.setcName(c_name);
					type.setcDes(c_des);
					type.setcBelong(Integer.valueOf(c_belong));
					type.setcGrade(Integer.valueOf(c_grade));
					type.setcEnable(Integer.valueOf(c_enable));
					
					type.setcAdmin("");
					type.setcAlias("");
					type.setcIsziying(1);
					type.setcStatus(1);
					type.setcMod("品类");
					type.setSources("erp");
					
					try {
						apitypeService.insertType4erp(type);
						//log
						ApiT_erp_log log = new ApiT_erp_log();
						log.setAction("insertType4erp");
						log.setGoods_id(c_code);
						SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						log.setInvoke_time(sFormat.format(new Date()).toString());
						apiT_erp_logService.insertT_erp_log(log);
						
						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "erp 添加分类成功！" + c_name + ","
								+ c_code);

					} catch (Exception e) {
						logger.error(e);
						map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
						map.put(Utils.MESSAGE, "erp 添加分类失败！" + c_name + ","
								+ c_code);
					}
				}
			}
		}
		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * erp分类id查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getTypesByShopId4erp")
	public void getTypesByShopId4erp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			String c_sid = request.getParameter("c_sid");
			List<ApiType> types = apitypeService.getTypesByShopId(Integer
					.valueOf(c_sid));
			if (types != null && types.size() > 0) {
				for (ApiType type : types) {
					Integer c_code = type.getcCode();
					Integer type_count = apitypeService
							.getGoodsCountByTypeId(c_code);
					type.setGoods_count(type_count);
				}
			}

			map.put("datas", types);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功！");
		} catch (Exception e) {
			logger.error(e);
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		// response
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	
}
